package cn.iocoder.yudao.module.erp.controller.admin.purchase;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.out.ErpPurchaseOutSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpStockDO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import cn.iocoder.yudao.module.erp.service.purchase.ErpPurchaseOutService;
import cn.iocoder.yudao.module.erp.service.purchase.ErpSupplierService;
import cn.iocoder.yudao.module.erp.service.stock.ErpStockService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;


@Tag(name = "管理后台 - ERP 基础出库")
@RestController
@RequestMapping("/erp/purchase-out")
@Validated
public class ErpPurchaseOutController {

    @Resource
    private ErpPurchaseOutService purchaseOutService;
    @Resource
    private ErpStockService stockService;
    @Resource
    private ErpProductService productService;
    @Resource
    private ErpSupplierService supplierService;
    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建ERP 基础出库")
    @PreAuthorize("@ss.hasPermission('erp:purchase-out:create')")
    public CommonResult<Long> createPurchaseOut(@Valid @RequestBody ErpPurchaseOutSaveReqVO createReqVO) {
        return success(purchaseOutService.createPurchaseOut(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新ERP 基础出库")
    @PreAuthorize("@ss.hasPermission('erp:purchase-out:update')")
    public CommonResult<Boolean> updatePurchaseOut(@Valid @RequestBody ErpPurchaseOutSaveReqVO updateReqVO) {
        purchaseOutService.updatePurchaseOut(updateReqVO);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新采购出库的状态")
    @PreAuthorize("@ss.hasPermission('erp:purchase-in:update-status')")
    public CommonResult<Boolean> updatePurchaseInStatus(@RequestParam("id") Long id,
                                                        @RequestParam("status") Integer status) {
        purchaseOutService.updatePurchaseOutStatus(id, status);
        return success(true);
    }


//    @DeleteMapping("/delete")
//    @Operation(summary = "删除ERP 基础出库")
//    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('erp:purchase-out:delete')")
//    public CommonResult<Boolean> deletePurchaseOut(@RequestParam("ids") Long id) {
//        purchaseOutService.deletePurchaseOut(id);
//        return success(true);
//    }

    @DeleteMapping("/delete")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除ERP 基础出库")
                @PreAuthorize("@ss.hasPermission('erp:purchase-out:delete')")
    public CommonResult<Boolean> deletePurchaseOutList(@RequestParam("ids") List<Long> ids) {
        purchaseOutService.deletePurchaseOutListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得ERP 基础出库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:purchase-out:query')")
    public CommonResult<ErpPurchaseOutRespVO> getPurchaseOut(@RequestParam("id") Long id) {
        ErpPurchaseOutDO purchaseOut = purchaseOutService.getPurchaseOut(id);
        if (purchaseOut == null) {
            return success(null);
        }
        List<ErpPurchaseOutItemsDO> purchaseOutItemList = purchaseOutService.getPurchaseOutItemListByOutId(id);
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(purchaseOutItemList, ErpPurchaseOutItemsDO::getProductId));
        return success(BeanUtils.toBean(purchaseOut, ErpPurchaseOutRespVO.class, VO ->
                VO.setItems(BeanUtils.toBean(purchaseOutItemList, ErpPurchaseOutRespVO.PurchaseOutItem.class, item -> {
                    ErpStockDO stock = stockService.getStock(item.getProductId(), item.getWarehouseId());
                    item.setStockCount(stock != null ? stock.getCount() : BigDecimal.ZERO);
                    MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                            .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()));
                }))));
    }

    @GetMapping("/page")
    @Operation(summary = "获得ERP 基础出库分页")
    @PreAuthorize("@ss.hasPermission('erp:purchase-out:query')")
    public CommonResult<PageResult<ErpPurchaseOutRespVO>> getPurchaseOutPage(@Valid ErpPurchaseOutPageReqVO pageReqVO) {
        PageResult<ErpPurchaseOutDO> pageResult = purchaseOutService.getPurchaseOutPage(pageReqVO);
        return success(buildPageResult(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出ERP 基础出库 Excel")
    @PreAuthorize("@ss.hasPermission('erp:purchase-out:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportPurchaseOutExcel(@Valid ErpPurchaseOutPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpPurchaseOutDO> list = purchaseOutService.getPurchaseOutPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "ERP基础出库.xls", "数据", ErpPurchaseOutRespVO.class,
                        BeanUtils.toBean(list, ErpPurchaseOutRespVO.class));
    }


    private PageResult<ErpPurchaseOutRespVO> buildPageResult(PageResult<ErpPurchaseOutDO> pageResult) {
        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty(pageResult.getTotal());
        }
        // 1.1 入库项
        List<ErpPurchaseOutItemsDO> purchaseOutItemList = purchaseOutService.getPurchaseOutItemListByOutIds(
                convertSet(pageResult.getList(), ErpPurchaseOutDO::getId));
        Map<Long, List<ErpPurchaseOutItemsDO>> purchaseOutItemMap = convertMultiMap(purchaseOutItemList, ErpPurchaseOutItemsDO::getOutId);
        // 1.2 产品信息
        Map<Long, ErpProductRespVO> productMap = productService.getProductVOMap(
                convertSet(purchaseOutItemList, ErpPurchaseOutItemsDO::getProductId));
        // 1.3 供应商信息
        Map<Long, ErpSupplierDO> supplierMap = supplierService.getSupplierMap(
                convertSet(pageResult.getList(), ErpPurchaseOutDO::getSupplierId));
        // 1.4 管理员信息
        Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
                convertSet(pageResult.getList(), purchaseOut -> Long.parseLong(purchaseOut.getCreator())));
        // 2. 开始拼接
        return BeanUtils.toBean(pageResult, ErpPurchaseOutRespVO.class, purchaseOut -> {
            purchaseOut.setItems(BeanUtils.toBean(purchaseOutItemMap.get(purchaseOut.getId()), ErpPurchaseOutRespVO.PurchaseOutItem.class,
                    item -> MapUtils.findAndThen(productMap, item.getProductId(), product -> item.setProductName(product.getName())
                            .setProductBarCode(product.getBarCode()).setProductUnitName(product.getUnitName()))));
            purchaseOut.setProductNames(CollUtil.join(purchaseOut.getItems(), "，", ErpPurchaseOutRespVO.PurchaseOutItem::getProductName));
            MapUtils.findAndThen(supplierMap, purchaseOut.getSupplierId(), supplier -> purchaseOut.setSupplierName(supplier.getName()));
            MapUtils.findAndThen(userMap, Long.parseLong(purchaseOut.getCreator()), user -> purchaseOut.setCreatorName(user.getNickname()));
        });
    }


}
